package com.yvan.dev2word;

import com.yvan.dev2word.db2word.vo.Table;
import com.yvan.dev2word.db2word.vo.TableDesc;
import com.yvan.dev2word.db2word.service.TableService;
import com.yvan.dev2word.postman2doc.utils.PostmanUtil;
import com.yvan.dev2word.swagger2doc.utils.Swagger2Utils;
import com.yvan.dev2word.swagger2doc.utils.VelocityUtil;
import com.yvan.dev2word.swagger2doc.vo.ApiDocVo;
import org.apache.commons.io.IOUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.context.Context;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;

@RestController
public class WordController {

    @Autowired
    private TableService tableService;

    @GetMapping("/swagger2word")
    public String swagger2word(HttpServletResponse response, String swaggerUrl, String apiExportName, String apiExportDir) {

        Template template = VelocityUtil.getTemplateInstance("templates/swagger2word.vm");
        String json = Swagger2Utils.getJson(swaggerUrl);
        if (StringUtils.isEmpty(json)) {
            return "swagger api 文档获取错误,请检查: " + swaggerUrl + ", 该地址是否正确";
        }
        ApiDocVo apiDocVo = Swagger2Utils.findInterface(json);
        assert apiDocVo != null;
        apiDocVo.setApiName(apiExportName);
        try {
            File file = new File(System.getProperty("java.io.tmpdir") + apiExportName + ".doc");
            Writer writer = new FileWriter(file);
            Context con = new VelocityContext();
            con.put("apiDoc", apiDocVo);
            template.merge(con, writer);
            writer.flush();
            writer.close();
            download(response, file, apiExportName + ".doc");
            file.delete();
            return "api文档生成成功,生成目录位置: " + apiExportDir;
        } catch (Exception e) {
            e.printStackTrace();
            return "api文档生成失败, 错误信息: " + e.getMessage();
        }
    }
    @GetMapping("/db2word")
    public String db2word(HttpServletResponse response,
                          String jdbcUrl, String jdbcUsername, String jdbcPassword,
                          String dbExportName, String excludeStr) {
        try {
            DriverManagerDataSource dataSource = tableService.createDataSource(jdbcUrl, jdbcUsername, jdbcPassword);

            List<Table> tableList = tableService.findAllTable(dataSource);

            for (Table table : tableList) {
                List<TableDesc> tableDescList = tableService.findByTableName(table.getTableName(), dataSource);
                if (!StringUtils.isEmpty(table.getTableComment())) {
                    table.setTableFullName(table.getTableComment().trim() + "(" + table.getTableName().trim() + ")");
                } else {
                    table.setTableFullName(table.getTableName().trim());
                }
                table.setDescList(tableDescList);
            }
            if (!StringUtils.isEmpty(excludeStr)) {
                String[] excludeArray = excludeStr.split(",");
                for (String exclude : excludeArray) {
                    tableList.removeIf(table -> table.getTableName().contains(exclude));
                }
            }

            Template template = VelocityUtil.getTemplateInstance("templates/db2word.vm");
            File file = new File(System.getProperty("java.io.tmpdir") + System.currentTimeMillis() + ".doc");
            Writer writer = new FileWriter(file);
            Context con = new VelocityContext();
            con.put("tableList", tableList);
            template.merge(con, writer);
            writer.flush();
            writer.close();
            System.out.println("over");

            download(response, file, dbExportName + ".doc");
            file.delete();
            return "数据库文档生成成功";

        } catch (Exception e) {
            e.printStackTrace();
            return "数据库文档生成失败, 错误信息: " + e.getMessage();
        }
    }

    private String download(HttpServletResponse response, File file, String fileName) throws UnsupportedEncodingException {
        // 如果文件名不为空，则进行下载
        // 如果文件存在，则进行下载
        if (!file.exists()) {
            return "文件不存在";
        }
        // 以流的形式下载文件。
        try {
            InputStream fis = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/msword");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
            return "success";

        } catch (Exception e) {
            System.out.println("Download  failed!");
            return "failed";
        }
    }
}
